package com.sq.partner.manager.controller;




import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sq.partner.manager.dao.ICoreDeptDao;
import com.sq.partner.manager.util.*;
import org.apache.log4j.Logger;
import org.apache.xml.resolver.apps.resolver;
import org.dom4j.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.CoinFeeConfig;
import com.sq.partner.manager.mybatis.model.CoinPlanConfig;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayConfig;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NocarPlan;
import com.sq.partner.manager.mybatis.model.NocarProd;
import com.sq.partner.manager.mybatis.model.SaleConfig;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradAgentInfoRela;
import com.sq.partner.manager.mybatis.model.TradEmailTemplate;
import com.sq.partner.manager.mybatis.model.TradInsuPlanGroup;
import com.sq.partner.manager.mybatis.model.TradPlanGroup;
import com.sq.partner.manager.mybatis.model.TradPlanSale;
import com.sq.partner.manager.mybatis.model.TradSaleAgent;
import com.sq.partner.manager.mybatis.model.TradSmsTemplate;
import com.sq.partner.manager.mybatis.model.TradeFeeCov;
import com.sq.partner.manager.service.CoinFeeConfigService;
import com.sq.partner.manager.service.CoinPlanConfigService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayConfigService;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.IGatewayNoCarProductService;
import com.sq.partner.manager.service.IGatewayNocarInsureService;
import com.sq.partner.manager.service.IGatewaySubChannelService;
import com.sq.partner.manager.service.INlifePlanConfigService;
import com.sq.partner.manager.service.ITradInsuPlanGroupService;
import com.sq.partner.manager.service.ITradPlanGroupService;
import com.sq.partner.manager.service.SaleConfigService;
import com.sq.partner.manager.service.TradEmailTemplateService;
import com.sq.partner.manager.service.TradPlanSaleService;
import com.sq.partner.manager.service.TradSmsTemplateService;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
/**
 *
 * @author guozizhou
 * @date 2015-04-18
 * 财险方案配置 noCarInsure
 */
@Controller
@RequestMapping("/noCarInsure")
public class NocarInsureController {

	private static Logger logger = LogUtil.getLog(NocarInsureController.class);
	@Resource
	TradPlanSaleService tradPlanSaleService;
	@Resource
	IGatewayInsureService gatewayInsureService;
	@Resource
	ITradInsuPlanGroupService insuPlanGroupService;
	@Resource
	ITradPlanGroupService plangroupService;
	@Resource
	IGatewayNoCarProductService noCarProductService ;
	@Resource
	IGatewayNocarInsureService  nocarInsureService ;
	@Resource
	private INlifePlanConfigService nlifePlanConfigService;
	@Resource
	private TradSmsTemplateService tradSmsTemplateService;
	@Resource
	private IGatewaySubChannelService subChannelService;
	@Resource
	private  IGatewayConfigService  gatewayConfigService;
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	@Resource
	private SaleConfigService saleConfigService;
	@Resource
	private CoinFeeConfigService coinFeeConfigService;
	@Resource
	private CoinPlanConfigService coinPlanConfigService;
	@Resource
	private TradEmailTemplateService tradEmailTemplateService;
	@Resource
	private ICoreDeptDao coreDeptDao;

	/**
	 * 跳转方案列表页面
	 */
	@RequestMapping(value = "/list")
	public String insureDefinition(ModelMap model,HttpServletRequest request) throws Exception {
		return "noCarProduct/insure/list";
	}

	//添加 投保方案成功后，传入一个参数标识在list页面提示
	@RequestMapping(value = "/success")
	public String noticeSuccess(HttpServletRequest request,String flag) throws Exception {
		request.setAttribute("flag", flag);
		logger.info("flag==========================="+flag);
		return "noCarProduct/insure/list";
	}
	//跳转至新增页面
	@RequestMapping(value = "/add")
	public String insureAdd(ModelMap model,HttpServletRequest request) throws Exception {
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		model.put("Accessorylist",Accessorylist );
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		newBSList = DictCache.remakeNewBussinessSource();
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		//初始化方案销售类型
		List<DictDto> agentTypes = DictCache.getDict(Constants.DICT_NOCAR_AGENT_TYPE);
		//电子保单文件方式
		List<DictDto> fileTypes = DictCache.getDict(Constants.DICT_FILE_TYPE);
		//初始化承保短信
		List<TradSmsTemplate> messageList = tradSmsTemplateService.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		//初始化注销短信
		List<TradSmsTemplate> cacelList = tradSmsTemplateService.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//回执类型
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_NOCAR_RECEIPT_TYPE);
		//电子批单类型
		List<DictDto>  edrnoTypes = DictCache.getDict(Constants.DICT_NOCAR_EDRNO_TYPE);
		//发票购方,1,投保人2,被保人3,接口传入
		List<DictDto> payEinvoices = DictCache.getDict(Constants.DICT_PAY_EINVOICE);
		/**方案号生成规则*/
		GatewayConfig gatewayConfig=gatewayConfigService.queryConfigByName(Constants.PTN_ENV);
		/**只有st显示不分大小写*/
		if(gatewayConfig!=null&&"ST".equalsIgnoreCase(gatewayConfig.getConfigValue())){
			model.put("ptnEnv", "display:''");
		}else{
			model.put("ptnEnv", "display:none");
		}
		model.put("payEinvoices", payEinvoices);
		model.put("edrnoTypes", edrnoTypes);
		model.put("receiptTypeLs", receiptTypeLs);
		model.put("newBSList", newBSList);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("channelList", channelList);
		model.put("messageList", messageList);
		model.put("cacelList", cacelList);
		model.put("agentTypes", agentTypes);
		model.put("fileTypes", fileTypes);
		return "noCarProduct/insure/add";
	}
	//跳转至编辑页面
	@RequestMapping(value = "/edit")
	public String insureEdit(ModelMap model,HttpServletRequest request,String planCode) throws Exception {
		request.setAttribute("planCode",planCode);
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		model.put("AccessoryEditlist",Accessorylist );
		//根据选择的控件编码显示
		NocarPlan ncp = new NocarPlan();
		ncp.setPlanCode(planCode);
		ncp = nocarInsureService.queryTradNocarPlanInfo(ncp);
		if(null!=ncp && StrUtil.isNotEmpty(ncp.getChannelCode()))
		{
			List<DictDto> channelList = getPageLoadSubDropList(Constants.DICT_CHANNEL_TYPE,ncp.getChannelCode());
			model.put("channelList", channelList);
		}
		if(null!=ncp && StrUtil.isNotEmpty(ncp.getChannelType()))
		{
			List<DictDto> newBSList = getPageLoadSubDropList(Constants.DICT_NEW_BUSINESS_SOURCE,ncp.getChannelType());
			newBSList = DictCache.remakeNewBussinessSource();
			model.put("newBSList", newBSList);
		}
		//发票购方,1,投保人2,被保人3,接口传入
		List<DictDto> payEinvoices = DictCache.getDict(Constants.DICT_PAY_EINVOICE);
		// 旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		// 归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//初始化承保短信
		List<TradSmsTemplate> messageList = tradSmsTemplateService.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		//初始化注销短信
		List<TradSmsTemplate> cacelList = tradSmsTemplateService.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//初始化方案销售类型
		List<DictDto> agentTypes = DictCache.getDict(Constants.DICT_NOCAR_AGENT_TYPE);
		//电子保单文件方式
		List<DictDto> fileTypes = DictCache.getDict(Constants.DICT_FILE_TYPE);
		//回执类型
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_NOCAR_RECEIPT_TYPE);
		//电子批单类型
		List<DictDto>  edrnoTypes = DictCache.getDict(Constants.DICT_NOCAR_EDRNO_TYPE);
		//两位和四位机构代码
		List<CoreDept> provenceDeptList = coreDeptDao.queryProvenceAndNextLevelDept();
		//车辆类型信息
		List<DictDto> carNatureList = DictCache.getDict("VHL_NLIFE_CAR_MANAGER");//使用的字典待确定
		// 渠道类型
		model.put("payEinvoices", payEinvoices);
		model.put("receiptTypeLs", receiptTypeLs);
		model.put("edrnoTypes", edrnoTypes);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("agentTypes", agentTypes);
		model.put("messageList", messageList);
		model.put("cacelList", cacelList);
		model.put("fileTypes", fileTypes);
		model.put("ptnEnv", "display:none");
		model.put("provenceDeptList", provenceDeptList);
		model.put("carNatureList", carNatureList);
		return "noCarProduct/insure/add";
	}

	//查询短信模板信息
	@RequestMapping(value = "/loadTemplate")
	public @ResponseBody TradSmsTemplate loadTemplate(String smsTemplateCode) throws Exception{
		return tradSmsTemplateService.queryTradeByCode(smsTemplateCode);
	}

	//跳转至复制添加页面
	@RequestMapping(value = "/copyadd")
	public String insureCopyAdd(ModelMap model,HttpServletRequest request,String planCode,String prodType) throws Exception {
		logger.info("===================="+planCode);
		request.setAttribute("planCode",planCode);
		request.setAttribute("prodType",prodType);
		NocarPlan ncp = new NocarPlan();
		ncp.setPlanCode(planCode);
		ncp = nocarInsureService.queryTradNocarPlanInfo(ncp);
		if(null!=ncp && StrUtil.isNotEmpty(ncp.getChannelCode()))
		{
			List<DictDto> channelList = getPageLoadSubDropList(Constants.DICT_CHANNEL_TYPE,ncp.getChannelCode());
			model.put("channelList", channelList);
		}
		if(null!=ncp && StrUtil.isNotEmpty(ncp.getChannelType()))
		{
			List<DictDto> newBSList = getPageLoadSubDropList(Constants.DICT_NEW_BUSINESS_SOURCE,ncp.getChannelType());
			newBSList = DictCache.remakeNewBussinessSource();
			model.put("newBSList", newBSList);
		}
		//初始化方案销售类型
		List<DictDto> agentTypes = DictCache.getDict(Constants.DICT_NOCAR_AGENT_TYPE);
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		model.put("Accessorylist",Accessorylist );
		//发票购方,1,投保人2,被保人3,接口传入
		List<DictDto> payEinvoices = DictCache.getDict(Constants.DICT_PAY_EINVOICE);
		// 旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		// 归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//初始化承保短信
		List<TradSmsTemplate> messageList = tradSmsTemplateService.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		//初始化注销短信
		List<TradSmsTemplate> cacelList = tradSmsTemplateService.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//电子保单文件方式
		List<DictDto> fileTypes = DictCache.getDict(Constants.DICT_FILE_TYPE);
		//回执类型
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_NOCAR_RECEIPT_TYPE);
		/**方案号生成规则*/
		GatewayConfig gatewayConfig=gatewayConfigService.queryConfigByName(Constants.PTN_ENV);
		//电子批单类型
		List<DictDto>  edrnoTypes = DictCache.getDict(Constants.DICT_NOCAR_EDRNO_TYPE);
		/**只有st显示不分大小写*/
		if(gatewayConfig!=null&&"ST".equalsIgnoreCase(gatewayConfig.getConfigValue())){
			model.put("ptnEnv", "display:''");
		}else{
			model.put("ptnEnv", "display:none");
		}
		// 渠道类型
		model.put("payEinvoices", payEinvoices);
		model.put("receiptTypeLs", receiptTypeLs);
		model.put("oldBSList", oldBSList);
		model.put("edrnoTypes", edrnoTypes);
		model.put("btcList", btcList);
		model.put("messageList", messageList);
		model.put("agentTypes", agentTypes);
		model.put("cacelList", cacelList);
		model.put("fileTypes", fileTypes);
		return "noCarProduct/insure/copyAdd";
	}
	/**
	 * //导出方案数据  authored by  JJB
	 * @param session
	 * @param request
	 * @param planCode
	 * @param response
	 * @throws Exception
	 */

	@RequestMapping(value = "/expPlan")
	public void expPlan(HttpSession session,HttpServletRequest request, String planCode,HttpServletResponse response) throws Exception {
		ServletOutputStream  outPutStream=null;
		final String userAgent = request.getHeader("USER-AGENT");
		String filename="财险方案导出.txt";
		//浏览器兼容性
		if(userAgent.indexOf("MSIE")!=-1){
			filename=java.net.URLEncoder.encode(filename, "UTF-8");//IE浏览器
		}else if(userAgent.indexOf("Mozilla")!=-1){
			filename=new String(filename.getBytes(),"ISO8859-1");//火狐浏览器
		}else{
			filename=java.net.URLEncoder.encode(filename, "UTF-8");
		}
		String[]  plans=choosePlans(planCode);
		/*查询产品数据*/
		Map<String,Object> map=new HashMap<String,Object>();
		map=queryPlans(plans);
		try{
			outPutStream=response.getOutputStream();
			response.setContentType("text/plain");
			response.setHeader("content-type", "text/html;charset=UTF-8");
			response.addHeader(
					"Content-Disposition",
					"attachment; filename="+filename);
			String  ss=FreeMarkerUtil.process("noCarPlan.ftl", map);
			outPutStream.write(ss.getBytes());
			outPutStream.flush();
		}catch(Exception e){
			throw  e;
		}finally{
			if(outPutStream!=null){
				outPutStream.close();
			}
		}
	}

	private Map<String, Object> queryPlans(String[] plans) throws Exception {
		// TODO Auto-generated method stub
		Map<String,Object> maps=new HashMap<String,Object>();
		maps.put("plans", plans);
		List<String> planSqls=new ArrayList<String>();
		List<String> groupSqls=new ArrayList<String>();
		List<String> infoSqls=new ArrayList<String>();
		List<String> saleSqls=new ArrayList<String>();
		List<String> subSqls=new ArrayList<String>();
		List<String> coinSqls=new ArrayList<String>();
		List<String> coinFeeSqls=new ArrayList<String>();
		List<String> saleConfigSqls=new ArrayList<String>();
		List<String> agentSqls=new ArrayList<String>();
		List<String> tradSaleSqls=new ArrayList<String>();
		/**方案**/
		List<Map<String, Object>>  nocarPlanList=nocarInsureService.searchNoCarPlansByplanCode(maps);
		for (Map<String, Object> map2 : nocarPlanList) {
			String agent_type =(String) map2.get("AGENT_TYPE");
			if("1".equals(agent_type)) {
				map2.put("STATUS", "0");
				map2.put("IS_PUSHED_SALES_INFO", "N");
			}
			String sql=getInsertSql(map2, "T_NOCAR_PLAN");
			planSqls.add(sql);
		}
		/**方案方案组关联**/
		List<Map<String, Object>>  groupList=insuPlanGroupService.impNlifeGroup1(maps);
		for (Map<String, Object> map2 : groupList) {
			String sql=getInsertSql(map2, "T_TRAD_INSU_PLAN_GROUP");
			groupSqls.add(sql);
		}
		/**代理信息*/
		List<Map<String, Object>>  infos=nlifePlanConfigService.impNlifeInfo(maps);
		for (Map<String, Object> map2 : infos) {
			String sql=getInsertSql(map2, "T_TRAD_AGENT_INFO");
			infoSqls.add(sql);
		}
		/**方案代理信息关联*/
		List<Map<String, Object>>  tradAgentInfoRelasList=nocarInsureService.impNocarRela(maps);
		for (Map<String, Object> map2 : tradAgentInfoRelasList) {
			String sql=getInsertSql(map2, "T_TRAD_AGENT_INFO_RELA");
			agentSqls.add(sql);
		}

		/**广分销售信息*/
		List<Map<String, Object>>  tradPlanSaleList= tradPlanSaleService.impNlifeSale(maps);
		for (Map<String, Object> map2 : tradPlanSaleList) {
			String sql=getInsertSql(map2, "T_TRAD_PLAN_SALE");
			saleSqls.add(sql);
		}
		/**广分销售信息（总对总个人代理）*/
		List<Map<String, Object>>  tradSaleAgentsList=tradPlanSaleService.searchTradSaleAgentsByplanCode(maps);
		for (Map<String, Object> map2 : tradSaleAgentsList) {
			String sql=getInsertSql(map2, "T_TRAD_PLAN_SALE");
			subSqls.add(sql);
		}

		/**网点信息**/
		List<Map<String, Object>> gatewaySubChannelsList=subChannelService.impNlifeSub(maps);
		for (Map<String, Object> map2 : gatewaySubChannelsList) {
			String sql=getInsertSql(map2, "T_GATEWAY_SUB_CHANNEL");
			subSqls.add(sql);
		}
		/**跟单配置关联**/
		List<Map<String, Object>>  coinPlanConfigsList=coinPlanConfigService.implCoinPlan(maps);
		for (Map<String, Object> map2 : coinPlanConfigsList) {
			String sql=getInsertSql(map2, "COIN_PLAN_CONFIG");
			coinSqls.add(sql);
		}
		/**共享保三费配置*/
		List<Map<String, Object>>  coinFeeConfigsList=coinFeeConfigService.implCoinFee(maps); //共享保三费配置
		for (Map<String, Object> map2 : coinFeeConfigsList) {
			String sql=getInsertSql(map2, "COIN_FEE_CONFIG");
			coinFeeSqls.add(sql);
		}
		/**跟单费用配置*/
		List<Map<String, Object>>  saleConfig=saleConfigService.implSaleConfigs(maps); //跟单费用配置
		for (Map<String, Object> map2 : saleConfig) {
			String sql=getInsertSql(map2, "SALE_FEE_CONFIG");
			saleConfigSqls.add(sql);
		}
		maps.put("nocarPlanList", planSqls);
		maps.put("tradInsuPlanGroupList", groupSqls);
		maps.put("tradAgentInfoList", infoSqls);
		maps.put("tradAgentInfoRelasList", agentSqls);
		maps.put("tradPlanSaleList", saleSqls);
		maps.put("tradSaleAgentsList", tradSaleSqls);
		maps.put("gatewaySubChannelsList", subSqls);
		maps.put("coinPlanConfigsList", coinSqls);
		maps.put("coinFeeConfigsList", coinFeeSqls);
		maps.put("saleConfigsList", saleConfigSqls);
		return maps;
	}
	/**循环map返回insert语句**/
	private String getInsertSql(Map<String, Object> map,String table){
		String sql="INSERT INTO " +table;
		String cloum=" (";
		String value=" (";
		if(map!=null){
			for (String key : map.keySet()) {
				if(key.equalsIgnoreCase("prod_code")){
					continue;
				}
				if("T_TRAD_AGENT_INFO_RELA".equalsIgnoreCase(table)&&key.startsWith("INFO_")){
					continue;
				}
				if(key.equalsIgnoreCase("prodCode")){
					cloum+="PROD_CODE,";
					value+="'"+map.get(key)+"',";
					continue;
				}
				if(key.equalsIgnoreCase("plan_group_id")){
					cloum+=key+",";
					value+="(SELECT TRAD.GROUP_ID  FROM T_TRAD_PLAN_GROUP  TRAD   LEFT JOIN T_NOCAR_PROD PROD ON  TRAD.PROD_TYPE=PROD.PROD_TYPE  LEFT JOIN T_NOCAR_PLAN  PLAN ON PLAN.PROD_CODE=PROD.PROD_CODE  WHERE PLAN.PLAN_CODE='"+map.get("INSU_PLAN_NO")+"' AND TRAD.IS_PROD_GROUP='1'),";
					continue;
				}
				if(key.equalsIgnoreCase("id")&&(table.equalsIgnoreCase("t_trad_agent_info")||table.equalsIgnoreCase("t_trad_agent_info_rela"))){
					cloum+=key+",";
					String seq="S_"+table+".NEXTVAL ,";
					value+=seq.replace("T_TRAD", "TRAD");
					continue;
				}
				if(key.equalsIgnoreCase("AGENT_INFO_ID")){
					cloum+=key+",";
					String sql1="(SELECT ID FROM T_TRAD_AGENT_INFO INFO WHERE  1=1 AND";
					if("3".equals(map.get("INFO_AGENT_TYPE"))){
						sql1+="  INFO.CHANNEL_CODE='"+map.get("INFO_CHANNEL_CODE")+"'AND INFO.USER_CODE='"+map.get("INFO_USER_CODE")+"' ) ,";
						value+=sql1;
					}
					if("4".equals(map.get("INFO_AGENT_TYPE"))){
						sql1+=" INFO.CHANNEL_CODE='"+map.get("INFO_CHANNEL_CODE")+"'AND INFO.SUB_CHANNEL_CODE='"+map.get("INFO_SUB_CHANNEL_CODE")+"' ) ,";
						value+=sql1;
					}
					if("5".equals(map.get("INFO_AGENT_TYPE"))){
						for (int i = 1; i < 6; i++) {
							if(map.get("KEY"+i)!=null){
								sql1+=" AND INFO.KEY"+i+"= "+map.get("INFO_KEY"+i)+",";
							}
						}
						value+=sql1;
					}
					continue;
				}
				if(key.equalsIgnoreCase("id")){
					cloum+=key+",";
					value+="(SELECT MAX("+key+")+1  from "+table+") ,";
					continue;
				}
				if(key.equalsIgnoreCase("oper_time")||key.equalsIgnoreCase("INSERT_TIME")||key.equalsIgnoreCase("UPDATE_TIME")||key.equalsIgnoreCase("UPRATE_TIME")){
					cloum+=key+",";
					value+="SYSDATE,";
					continue;
				}
				cloum+=key+",";
				if(map.get(key)!=null){
					value+="'"+map.get(key)+"',";
				}else{
					value+=map.get(key)+",";
				}

			}
			cloum=cloum.substring(0,cloum.length()-1)+" )";
			value=value.substring(0,value.length()-1)+" )";
		}
		return sql+cloum+" VALUES "+value;
	}
	/**
	 * 方案号转化为数组
	 * @param planCode
	 * @return
	 */
	private String[] choosePlans(String planCode) {
		// TODO Auto-generated method stub
		if(StrUtil.isEmpty(planCode)){
			return null;
		}
		String[] strs=planCode.split(",");
		return strs;
	}

	/**
	 * 加载投保方案列表页面
	 */
	@RequestMapping(value = "/loadInsuPlan")
	public @ResponseBody Page<NocarPlan> InsuPlan(HttpSession session,Integer size,Integer current,String prodCode,String planCode,String partnerCode,String planName) throws Exception{
		Page<NocarPlan> page=new Page<NocarPlan>();
		page.setCurrent(current);
		page.setSize(size);
		NocarPlan ncp=new NocarPlan();
		ncp.setPlanCode(planCode);
		ncp.setPartnerCode(partnerCode);
		ncp.setPlanName(planName);
		ncp.setProdCode(prodCode);
		/**是否有导出权限用户判断**/
		boolean flag=false;
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String currentUser=gatewayuser.getUserCode();
		String usersConfig=Config.getProp("imple.nlife.userCodes");
		String[] codes=choosePlans(usersConfig);
		if(codes!=null&&codes.length>0){
			flag=Arrays.asList(codes).contains(currentUser);
		}
		page.setDepts(gatewayuser.getDepts());
		Map<String, Object>map=page.getMap();
		if(map==null){
			map=new HashMap<String, Object>();
		}
		map.put("depts", gatewayuser.getDepartmentStr());
		page.setMap(map);
		page.setType(ncp);
		page.setObj(flag);
		return nocarInsureService.queryNocarPlanPage(page);
	}


	private String[] separete(String usersConfig) {
		if(StrUtil.isEmpty(usersConfig)){
			return null;
		}
		String[] strs=usersConfig.split(",");
		return strs;
	}

	/**
	 * 加载所有 投保单位
	 * @param size
	 * @param current
	 * @return
	 * @throws Exception
	 * loadChannelInfo
	 */
	@RequestMapping(value = "/loadChannelInfo")
	public @ResponseBody Page<GatewayChannelInfo> loadChannelInfo(HttpSession session,Integer size,Integer pageIndex,String channelCode,String channelName) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);

		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);
		Page<GatewayChannelInfo> p=gatewayInsureService.queryPageForGatewayChannelInfo(page);
		return p;
	}
	/**
	 * 方案界面加载所有 投保单位
	 * @param size
	 * @param current
	 * @return
	 * @throws Exception
	 * loadChannelInfo
	 */
	@RequestMapping(value = "/loadChannelInfo1")
	public @ResponseBody Page<GatewayChannelInfo> loadChannelInfo1(HttpSession session,Integer size,Integer pageIndex,String channelCode,String channelName) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);

		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);
		Page<GatewayChannelInfo> p=nlifePlanConfigService.queryChannelInfoPageByCriteria1(page);
		return p;
	}
	/**
	 * 加载所有 产品列表
	 */
	@RequestMapping(value = "/loadTradProdInst")
	public @ResponseBody Page<NocarProd> queryAllTradProdInst(Integer size,Integer pageIndex,String tradProdCode,String tradProdDesc,String VstartDate,String VendDate) throws Exception{
		Page<NocarProd> page=new Page<NocarProd>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		NocarProd noCar=new NocarProd();
		//判断空
		noCar.setProdCode(tradProdCode);
		noCar.setProdName(tradProdDesc);
		noCar.setVstartDate(VstartDate);
		noCar.setVendDate(VendDate);
		page.setType(noCar);
		Page<NocarProd> page2=noCarProductService.queryPageForNocarInsure(page);
		return page2;
	}


	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 */
	@RequestMapping(value = "/loadCoreDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(HttpSession session, Integer size,Integer pageIndex,String deptCode,String deptCNname,String channelCode) throws Exception{
		GatewayUser gatewayuser = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setObj(gatewayuser);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCNname);
		page.setType(dept);
		Page<CoreDept> page2=gatewayInsureService.queryPageForCoreDept(page,channelCode);
		return page2;
	}


	/**
	 * 添加 投保方案
	 */
	@RequestMapping(value = "/addTradInsuPlan")
	public @ResponseBody Result addTradInsuPlan(HttpSession session,
												String fileType,String prodCode, String prodName, String planName,String partnerCode, String channelCode, String channelType,String serviceCode,String serviceName,
												BigDecimal commRate, String isSeeMoney,String empNo,String empName, String teamCode, String teamName, String bsnsType, String newBsnsType,
												String deptCode,String agentNo, String specialArran, String status, String isMessage,String messageReceiver,
												String messageTemplate, String prodType,String protocolNo,String isEpolicy,String isPrintCard,String cardType,
												String cardApplicant,String EpolicyInvoice, String DredgePay,String EpolicyMali,String MailTemplate ,String selectAccessorylistStr,String DownloadWay,String planType,String saleArry,String isCancelMessage,String cancelReceiver,String cancelTemplate,String agentFeeConfig,String agentType,BigDecimal businessPerformanceRate,
												BigDecimal marketPreserveRate,String specialConfigType,Boolean isProprod,String invockLink,String dentification,String isReceipt,String receiptType,String isedrno, String edrnoType,String isInsuranceEinvoice,String payEinvoice,String channelFlag,String isEConfirm,String isPushedSalesInfo)
			throws Exception {
		//首先进行非空、格式校验
		if(StrUtil.isEmpty(planName)){
			return Result.error("请输入投保方案名称");
		}
		if(StrUtil.isEmpty(prodCode)){
			return Result.error("请选择产品编号");
		}

		NocarProd prod2 =noCarProductService.queryNocarTradProdInstById(prodCode);
		if(StrUtil.isEmpty(partnerCode)){
			return Result.error("请选择合作伙伴代码");
		}
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(agentType)&&!"4".equals(agentType)&&!"6".equals(agentType)&&!"1".equals(channelFlag) && !"5".equals(agentType)){
			if(StrUtil.isEmpty(deptCode)){
				return Result.error("请选择出单机构");
			}
			if(StrUtil.isEmpty(channelCode)){
				return Result.error("请输入归属渠道");
			}
			if(StrUtil.isEmpty(channelType)){
				return Result.error("请输入渠道类型");
			}
			if(StrUtil.isEmpty(newBsnsType)){
				return Result.error("请输入新业务来源");
			}
			if(StrUtil.isEmpty(bsnsType)){
				return Result.error("请输入原业务来源");
			}
		}
		if(!"2".equals(agentFeeConfig)){
			if(null == commRate){
				return Result.error("请输入手续费比例");
			}else{
				Pattern pattern = Pattern.compile("([1-9]\\d{0,15}|0)(\\.\\d{1,6})?");
				Matcher matcher = pattern.matcher(commRate.toString());
				if(!matcher.matches()){
					return Result.error("手续费比例为长度不超过16位数字且最多保留6位小数的有效数字");
				}
				float tem = commRate.floatValue();
				if (!(0 <= tem && tem <= 1)) {
					return Result.error("手续费比例：只能录入大于等于0且小于等于1的数字！");
				}
			}
		}
		//产品销售类型为代理类型
		if("3".equals(agentType)||("4".equals(agentType)&&!"1".equals(channelFlag))){
			if("1".equals(status)){
				return Result.error("方案添加时，方案销售类型为代理类型则方案不能置为有效状态");
			}
		}
		if(!"1".equals(channelFlag)){
			//1、合作伙伴代理3、个人代理4、总对总代理
			if(!"3".equals(agentType)&&!"4".equals(agentType)&&!"6".equals(agentType) && !"5".equals(agentType)){
				if(StrUtil.isEmpty(serviceCode)){
					return Result.error("请输入服务代码");
				}
				if(StrUtil.isEmpty(empNo)){
					return Result.error("请输入业务员代码");
				}
				//原业务来源为19002-代理或19003-经纪，则代理人代码和代理协议号必填，其他非必填
				if("19002".equals(bsnsType)||"19003".equals(bsnsType)){
					if(StrUtil.isEmpty(agentNo)){
						return Result.error("请输入代理人代码");
					}
					if(StrUtil.isEmpty(protocolNo)){
						return Result.error("请输入代理协议号");
					}
				}
			}
		}
		//合作伙伴代理时校验销售渠道信息是否有效
		if("1".equals(agentType) &&  !"1".equals(channelFlag)) {
			List<DictDto> newBusinessSource = DictCache.getDict("new_business_source");
			
			Map<String,String> map = new HashMap<String, String>();
			SimpleDateFormat dateformat = new SimpleDateFormat("0000yyyyMMddHHmmss");
			String AGENTTYPE = getAgentTypeByNewBsnsType(newBsnsType,newBusinessSource);
			String SERIALDECIMAL = dateformat.format(System.currentTimeMillis());
			String CHANNELNAME = channelType.substring(0,1);
			map.put("SERIALDECIMAL",SERIALDECIMAL);
			map.put("COMCODE",deptCode);  //机构代码
			map.put("BUSINESSSOURCE",newBsnsType); //业务来源
			map.put("CHANNELNAME",CHANNELNAME); //渠道类型
			map.put("AGENTTYPE",AGENTTYPE); //代理类型
			map.put("USERCODE",empNo); //业务员代码
			map.put("TEAMCODE",teamCode); //团队代码
			map.put("AGENTCODE",agentNo); //中介代码
			map.put("AGREEMENTNO",protocolNo); //协议代码
			map.put("SERVICECODE",serviceCode); //服务代码
			map.put("PRODCODE",prod2.getProdType()); //产品代码
			String xml="";
			String responseXml="";
			xml=FreeMarkerUtil.process("/saleChannelInfo.ftl", map);
			logger.debug("请求30005接口的报文:"+xml);
			responseXml= HttpConnectorUtil.interaction(Config.getProp("salemanage.check.url"),xml,partnerCode,Constants.GW_CH_TX_30005);
			logger.debug("销管校验返回报文"+responseXml);
			Document doucument = DocumentHelper.parseText(responseXml);
			Element element = doucument.getRootElement();
			//解析报文校验查询是否成功
			String resultCode = selectSingleNodeByRoot(element , "/XML/HEAD/RESMSGCODE");

			if("0001".equals(resultCode)){
				String SALESMSG = selectSingleNodeByRoot(element , "/XML/BODY/SALESMSG");
				String AGENTMSG = selectSingleNodeByRoot(element , "/XML/BODY/AGENTMSG");
				String AGREEMENTMSG = selectSingleNodeByRoot(element , "/XML/BODY/AGREEMENTMSG");
				String SERVICECODEMSG = selectSingleNodeByRoot(element , "/XML/BODY/SERVICECODEMSG");
				String AGENTSALESMSG = selectSingleNodeByRoot(element , "/XML/BODY/AGENTSALESMSG");
				String errorMsg = SALESMSG + AGENTMSG + AGREEMENTMSG + SERVICECODEMSG +AGENTSALESMSG;
				return Result.error(errorMsg);
			}
		}
		cancelTemplate=URLDecoder.decode(cancelTemplate, "UTF-8");

		//是否电子保单
		if(StrUtil.isEmpty(isEpolicy)){
			return Result.error("请选择是否电子保单");
		}
		//是否发送电子邮件
		if(StrUtil.isEmpty(EpolicyMali)){
			return Result.error("请选择是否发送电子保单");
		}
		//是否发送电子发票

		if(StrUtil.isEmpty(EpolicyInvoice)){
			return Result.error("请选择是否发送电子发票");
		}
		//发送邮件模板
		if(EpolicyMali=="1" && MailTemplate.length()==0){
			return Result.error("请输入邮件模板");
		}
		if(DictCache.statusCheck("new_business_source", newBsnsType) == false ){
			return Result.error("此业务来源"+ newBsnsType + "已停用，请核实修改。");
		}
		MailTemplate = URLDecoder.decode(MailTemplate, "UTF-8");
		/*//是否开通支付平台
		if(StrUtil.isEmpty(DredgePay)){
			return Result.error("请选择是否开通支付平台");
		}*/

		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				String id=jsonElement.getAsJsonObject().get("id").getAsString();
				JsonElement cardapplicant=jsonElement.getAsJsonObject().get("cardapplicant");
				if(cardapplicant==null){
					ids=ids+id+",";
				}

			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}
		}
		//是否打印单证,当“是否打印单证”的值为“是”时，单证领用人可输入( "":请选择,"Y":是，"N":否)
		if(StrUtil.isEmpty(isPrintCard)){
			return Result.error("是否打印单证不能为空");
		}else{
			if("Y".equals(isPrintCard)){
				if(!"3".equals(agentType)&&!"4".equals(agentType)){
					if(StrUtil.isEmpty(cardApplicant)){
						return Result.error("单证领用人不能为空");
					}
				}
			}
		}
		//当“是否发送短信”的值为“是”时，短信模板配置
		if("Y".equals(isMessage)){
			if(StrUtil.isEmpty(messageReceiver)){
				return Result.error("请选择短信接收人");
			}
			if(StrUtil.isEmpty(messageTemplate)){
				return Result.error("短信模板配置不能为空");
			}
		}else{
			messageReceiver="";
		}
//		NocarPlan tem  = new NocarPlan();
		NocarPlan ncp  = new NocarPlan();
		String planflag="NOCAR";
		String isFlag="-";
		if (isProprod) {
			planflag="CIC"+prod2.getProdType();
			isFlag="";
		}
		NocarPlan tem = nocarInsureService.getMaxPlanCodeFromDB(planflag+"%");
		if (null == tem||StrUtil.isEmpty(tem.getPlanCode())) {
			ncp.setPlanCode(planflag+isFlag+"00001");
		} else {
			String maxNo = tem.getPlanCode().substring(tem.getPlanCode().length()-5);
			logger.info("----------------------------------"+ maxNo);
			int nextNoVal = Integer.parseInt(maxNo);
			nextNoVal = nextNoVal + 1;
			logger.info("-------------------------------------"+ nextNoVal);
			// 不足5位，补0
			String nextInsuPlanNo = (planflag+isFlag).concat(String.format("%05d",nextNoVal));
			ncp.setPlanCode(nextInsuPlanNo);
		}
		ncp.setProdCode(prodCode);
		ncp.setPlanName(planName);
		ncp.setPartnerCode(partnerCode);
		ncp.setChannelCode(channelCode);
		ncp.setChannelType(channelType);
		ncp.setServiceCode(serviceCode);
		ncp.setServiceName(serviceName);
		ncp.setCommRate(commRate);
		ncp.setIsMessage(isMessage);
		ncp.setEmpNo(empNo);
		ncp.setEmpName(empName);
		ncp.setTeamCode(teamCode);
		ncp.setTeamName(teamName);
		ncp.setBsnsType(bsnsType);
		ncp.setNewBsnsType(newBsnsType);
		ncp.setDeptCode(deptCode);
		ncp.setAgentNo(agentNo);
		ncp.setSpecialArran(specialArran);
		ncp.setStatus(status);
		ncp.setAgentType(agentType);
		ncp.setAgentFeeConfig(agentFeeConfig);
		ncp.setIsSeeMoney(isSeeMoney);
		ncp.setProtocolNo(protocolNo);
		ncp.setMessageReceiver(messageReceiver);
		ncp.setMessageTemplate(messageTemplate);
		ncp.setIsEpolicy(isEpolicy);
		ncp.setInsertTime(new Date());
		ncp.setIsPrintCard(isPrintCard);
		ncp.setCardType(cardType);
		ncp.setCardApplicant(cardApplicant);
		ncp.setEpolicyInvoice(EpolicyInvoice);
		ncp.setDredgePay(DredgePay);
		ncp.setEpolicyMali(EpolicyMali);
		ncp.setMailTemplate(MailTemplate);
		ncp.setIdStr(ids);
		ncp.setDownloadWay(DownloadWay);
		ncp.setIsCancelMessage(isCancelMessage);
		ncp.setCancelReceiver(cancelReceiver);
		ncp.setCancelTemplate(cancelTemplate);
		ncp.setFileType(fileType);
		ncp.setMarketPreserveRate(marketPreserveRate);
		ncp.setBusinessPerformanceRate(businessPerformanceRate);
		ncp.setSpecialConfigType(specialConfigType);
		ncp.setInvockLink(invockLink);
		ncp.setDentification(dentification);
		ncp.setIsReceipt(isReceipt);
		ncp.setReceiptType(receiptType);
		ncp.setIsedrno(isedrno);
		ncp.setEdrnoType(edrnoType);
		ncp.setIsInsuranceEinvoice(isInsuranceEinvoice);
		ncp.setPayEinvoice(payEinvoice);
		ncp.setIsEConfirm(isEConfirm);
		ncp.setIsPushedSalesInfo(isPushedSalesInfo);
		boolean flag = nocarInsureService.addNocarPlan(ncp);
		if (flag) {
			logger.info("==========================添加投保方案成功=============================");
			// 根据方案对应的产品的产品类型，查询相应方案组信息,将该方案和方案组信息维护到方案与方案组关联表
			// 根据产品类型得到方案组ID
			TradPlanGroup gp = new TradPlanGroup();
			gp.setProdType(prodType);
			TradPlanGroup pg = plangroupService.queryTradPlanGroupID(gp);
			// 维护方案与方案组关联表
			if(pg!=null){
				TradInsuPlanGroup group = new TradInsuPlanGroup();
				group.setInsuPlanNumber(ncp.getPlanCode());// insuPlanNo; //产品类型代码
				group.setPlanGroupId(StrUtil.getVal(pg.getGroupId()));
				group.setRequired("0");
				boolean f = insuPlanGroupService.addTradInsuPlanGroup(group);
				if (!f) {
					return Result.error("维护方案与方案组关联出错");
				}
			}
			//判断是否出单机构是否是广东分公司
			if(StrUtil.isNotEmpty(deptCode)){
				if(deptCode.startsWith("44")){
					addTradSale(ncp.getPlanCode(), planType, saleArry);
				}
			}
			Map<String,String>  resultMap =new  HashMap<String,String>();
			resultMap.put("InsuPlanNo", ncp.getPlanCode());
			resultMap.put("AgentType", agentType);
			resultMap.put("agentFeeConfig", agentFeeConfig);
			return Result.successAndData("添加成功",resultMap);
		} else {
			logger.info("==========================添加投保方案失败=============================");
			return Result.error("添加失败");
		}
	}



	/**
	 * 删除投保方案，只能删除 无效 状态数据，同时，需要删除方案与方案组的关联
	 * @param tp
	 * @param insuPlanNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delInsuPlan")
	public @ResponseBody Result deleteTradInsuPlan(NocarPlan ncp,String planCode,String channelCode,HttpSession session) throws Exception{

		GatewayUser gatewayuser = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isEmpty(planCode)){
			return Result.error("投保方案号不能为空");
		}else{
			ncp.setPlanCode(planCode);
			ncp.setPartnerCode(channelCode);
			NocarPlan result = nocarInsureService.queryTradNocarPlanInfo(ncp);
			String userdepts=gatewayuser.getDepartmentStr();
			if(!"'00'".equals(userdepts)){
				GatewayChannelInfo info= channelInfoConfigService.queryChannelInfoByChannelCode(result.getPartnerCode());
				if("00".equals(info.getDeptCode())){
					return Result.error("分公司用户不允许删除总公司方案");
				}
			}
			String status = result.getStatus();
			if(1==Integer.parseInt(status)){
				return Result.error("该方案状态为有效，不能删除");
			}else{
				boolean flag = nocarInsureService.delTradNocarPlan(planCode,channelCode);
				if(flag){
					//删除方案组关联
					insuPlanGroupService.deleteTradNocarPlanGroupByPlanCode(planCode);
					return Result.success("删除成功");
				}else{
					return Result.error("删除失败");
				}
			}
		}
	}


	/**
	 * 加载 投保方案信息
	 * @param tp
	 * @param insuPlanNo
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/loadInsuPlanInfo")
	public @ResponseBody String queryInsuPlanInfo(NocarPlan ncp,String planCode,HttpSession session) throws Exception{
		ncp.setPlanCode(planCode);
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String,Object> map = nocarInsureService.queryMapTradNocarPlanInfo(ncp);
		GatewayChannelInfo info= channelInfoConfigService.queryChannelInfoByChannelCode((String) map.get("PARTNERCODE"));
		map.put("thirdPlan", info.getIsThirdPlan());
		map.put("channelFlag", info.getChannelFlag());
		/**分公司人员操作总公司方案*/
		if(!"'00'".equals(user.getDepartmentStr())){
			/*GatewayChannelInfo channleInfo=(GatewayChannelInfo)map.get("planChannelInfo");*/
			if("00".equals(info.getDeptCode())){
				map.put("isBanchs", true);
			}
		}
		//承保短信模板
		String messageTemplate = (String) map.get("MESSAGETEMPLATE");
		if(!"".equals(messageTemplate) && null != messageTemplate){
			String messageTemplate_val = (tradSmsTemplateService.queryTradeByCode(messageTemplate)).getSmsTemplateText();
			map.put("messageTemplate_val", messageTemplate_val);
		}
		//注销短信模板
		String cancelTemplate = (String) map.get("CANCELTEMPLATE");
		if(!"".equals(cancelTemplate) && null != cancelTemplate){
			String cancelTemplate_val = (tradSmsTemplateService.queryTradeByCode(cancelTemplate)).getSmsTemplateText();
			map.put("cancelTemplate_val", cancelTemplate_val);
		}
		String agentType= (String) map.get("AGENTTYPE");
		String isEpolicyMali=(String) map.get("EPOLICYMALI");
		if(isEpolicyMali==null){
			isEpolicyMali="2";
		}
		String isEConfirm = (String) map.get("ISECONFIRM");
		map.put("ISECONFIRM", isEConfirm);
		map.put("EPOLICYMALI", isEpolicyMali);
		String isEpolicy=(String) map.get("ISEPOLICY");
		if(isEpolicy==null){
			isEpolicy="S";
		}
		map.put("ISEPOLICY", isEpolicy);
		String idStr=(String) map.get("IDSTR");
		String[] ids=null;
		if(idStr!=null){
			ids=idStr.split(",");
		}
		//“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		map.put("Accessorylist", Accessorylist);
		map.put("ids", ids);
		//获取销售类型信息
		Map<String, String> salemap=new HashMap<String, String>();
		salemap.put("planCode", planCode);
		List<TradPlanSale> sales=tradPlanSaleService.queryTrade(salemap);
		if(sales!=null&&sales.size()>0){
			map.put("sales", sales);
			/**销售人员字典*/
			List<DictDto> dictDtos=DictCache.getDict("sale_men_type");
			for (TradPlanSale tradPlanSale : sales) {
				for (DictDto dictDto : dictDtos) {
					if(StrUtil.isNotEmpty(tradPlanSale.getPersonType())&&tradPlanSale.getPersonType().equals(dictDto.getCode())){
						tradPlanSale.setPersonTypeName(dictDto.getCodeName());
					}
				}
			}
			List<DictDto> dictDtos1=DictCache.getDict("sales_type");
			for (TradPlanSale tradPlanSale : sales) {
				for (DictDto dictDto : dictDtos1) {
					if(tradPlanSale.getSaleType().equals(dictDto.getCode())){
						tradPlanSale.setSaleTypeName(dictDto.getCodeName());
					}
				}
			}
		}
		if("3".equals(agentType)||"4".equals(agentType)){
			List<Map> list = this.gatewayInsureService.queryTradAgentInfoByInsuPlanNo(planCode);
			if(!list.isEmpty()){
				List<Map> list1= new ArrayList<Map>();
				for (Map map2 : list) {
					Map<String,String> newmap = new HashMap<String,String>();
					String id = map2.get("ID")+"";
					String cardapplicant = map2.get("CARDAPPLICANT")+"";
					String market=map2.get("MARKET")+"";
					String business=map2.get("BUSINESS")+"";
					String value = map2.get("COMMRATE")+"";
					newmap.put("id", id);
					newmap.put("cardapplicant", cardapplicant);
					newmap.put("value", value);
					newmap.put("market", market);
					newmap.put("business", business);
					list1.add(newmap);
					map.put("map", list1);
				}
			}
		}

		String jsonStr = JsonUtils.toJson(map);
		return jsonStr;
	}


	/**
	 * 修改方案信息
	 */
	@RequestMapping(value = "/updateInsuPlanInfo")
	public @ResponseBody Result modifyInsuPlan(HttpSession session,String fileType,String planCode,
											   String prodCode, String prodName, String planName,
											   String partnerCode, String channelCode, String channelType,
											   String serviceCode, String serviceName, BigDecimal commRate, String isSeeMoney,
											   String empNo, String empName, String teamCode, String teamName, String bsnsType, String newBsnsType, String deptCode,
											   String agentNo, String specialArran, String status,
											   String isMessage,String messageReceiver,String messageTemplate,
											   String prodType,String protocolNo,String isEpolicy,String isPrintCard,String cardType,
											   String cardApplicant, String EpolicyInvoice, String DredgePay,String EpolicyMali,String MailTemplate ,String selectAccessorylistStr,String DownloadWay,String isCancelMessage,String cancelReceiver,String cancelTemplate,
											   String agentFeeConfig,String agentType,BigDecimal businessPerformanceRate,
											   BigDecimal marketPreserveRate,
											   String specialConfigType,String invockLink,String dentification
			,String isReceipt,String receiptType,String isedrno, String edrnoType,String isInsuranceEinvoice,String payEinvoice,String channelFlag,String isEConfirm,String isPushedSalesInfo
	)
			throws Exception {
		cancelTemplate=URLDecoder.decode(cancelTemplate, "UTF-8");
		// 首先进行非空、格式校验
		if (StrUtil.isEmpty(planName)) {
			return Result.error("请输入投保方案名称");
		}
		if (StrUtil.isEmpty(prodCode)) {
			return Result.error("请选择产品编号");
		}
		NocarProd prod2 =noCarProductService.queryNocarTradProdInstById(prodCode);

		if(StrUtil.isEmpty(partnerCode)){
			return Result.error("请选择合作伙伴代码");
		}
		if(!"1".equals(channelFlag)){
			//1、合作伙伴代理3、个人代理4、总对总代理
			if(!"3".equals(agentType)&&!"4".equals(agentType)&&!"6".equals(agentType) && !"5".equals(agentType)){
				if(StrUtil.isEmpty(deptCode)){
					return Result.error("请选择出单机构");
				}
				if (StrUtil.isEmpty(channelCode)) {
					return Result.error("请输入归属渠道");
				}
				if (StrUtil.isEmpty(channelType)) {
					return Result.error("请输入渠道类型");
				}
				if (StrUtil.isEmpty(newBsnsType)) {
					return Result.error("请输入新业务来源");
				}
				if (StrUtil.isEmpty(bsnsType)) {
					return Result.error("请输入原业务来源");
				}
			}
		}
		if(!"2".equals(agentFeeConfig)){
			if (null == commRate) {
				return Result.error("请输入手续费比例");
			} else {
				Pattern pattern = Pattern
						.compile("([1-9]\\d{0,15}|0)(\\.\\d{1,6})?");
				Matcher matcher = pattern.matcher(commRate.toString());
				if (!matcher.matches()) {
					return Result.error("手续费比例为长度不超过16位数字且最多保留6位小数的有效数字");
				}
				float tem = commRate.floatValue();
				if (!(0 <= tem && tem <= 1)) {
					return Result.error("手续费比例：只能录入大于等于0且小于等于1的数字！");
				}
			}
		}
		//产品销售类型为代理类型
		if("3".equals(agentType)||"4".equals(agentType)){
			if("1".equals(status)){
				if(nocarInsureService.proxyInfoIsEmpty(planCode)){
					return Result.error("代理信息为空 时不能将方案状态置为有效,请配置代理信息");
				}
			}
		}
		if(!"1".equals(channelFlag)){
			//1、合作伙伴代理3、个人代理4、总对总代理
			if(!"3".equals(agentType)&&!"4".equals(agentType)&&!"6".equals(agentType) && !"5".equals(agentType)){
				if(StrUtil.isEmpty(serviceCode)){
					return Result.error("请输入服务代码");
				}
				if(StrUtil.isEmpty(empNo)){
					return Result.error("请输入业务员代码");
				}
				//原业务来源为19002-代理或19003-经纪，则代理人代码和代理协议号必填，其他非必填
				if("19002".equals(bsnsType)||"19003".equals(bsnsType)){
					if(StrUtil.isEmpty(agentNo)){
						return Result.error("请输入代理人代码");
					}
					if(StrUtil.isEmpty(protocolNo)){
						return Result.error("请输入代理协议号");
					}
				}
			}
		}
		//合作伙伴代理时校验销售渠道信息是否有效
		if("1".equals(agentType)  &&  !"1".equals(channelFlag)) {
			List<DictDto> newBusinessSource = DictCache.getDict("new_business_source");
			if(DictCache.statusCheck("new_business_source", newBsnsType) == false ){
				return Result.error("此业务来源"+ newBsnsType + "已停用，请核实修改。");
			}
			Map<String,String> map = new HashMap<String, String>();
			SimpleDateFormat dateformat = new SimpleDateFormat("0000yyyyMMddHHmmss");
			String AGENTTYPE = getAgentTypeByNewBsnsType(newBsnsType,newBusinessSource);
			String SERIALDECIMAL = dateformat.format(System.currentTimeMillis());
			String CHANNELNAME = channelType.substring(0,1);
			map.put("SERIALDECIMAL",SERIALDECIMAL);
			map.put("COMCODE",deptCode);  //机构代码
			map.put("BUSINESSSOURCE",newBsnsType); //业务来源
			map.put("CHANNELNAME",CHANNELNAME); //渠道类型
			map.put("AGENTTYPE",AGENTTYPE); //代理类型
			map.put("USERCODE",empNo); //业务员代码
			map.put("TEAMCODE",teamCode); //团队代码
			map.put("AGENTCODE",agentNo); //中介代码
			map.put("AGREEMENTNO",protocolNo); //协议代码
			map.put("SERVICECODE",serviceCode); //服务代码
			map.put("PRODCODE",prod2.getProdType()); //产品代码
			String xml="";
			String responseXml="";
			xml=FreeMarkerUtil.process("/saleChannelInfo.ftl", map);
			logger.debug("请求30005接口的报文:"+xml);
			responseXml= HttpConnectorUtil.interaction(Config.getProp("salemanage.check.url"),xml,partnerCode, Constants.GW_CH_TX_30005);
			logger.debug("销管校验返回报文"+responseXml);
			Document doucument = DocumentHelper.parseText(responseXml);
			Element element = doucument.getRootElement();
			///解析报文校验查询是否成功
			String resultCode = selectSingleNodeByRoot(element , "/XML/HEAD/RESMSGCODE");
			if("0001".equals(resultCode)){
				String SALESMSG = selectSingleNodeByRoot(element , "/XML/BODY/SALESMSG");
				String AGENTMSG = selectSingleNodeByRoot(element , "/XML/BODY/AGENTMSG");
				String AGREEMENTMSG = selectSingleNodeByRoot(element , "/XML/BODY/AGREEMENTMSG");
				String SERVICECODEMSG = selectSingleNodeByRoot(element , "/XML/BODY/SERVICECODEMSG");
				String AGENTSALESMSG = selectSingleNodeByRoot(element , "/XML/BODY/AGENTSALESMSG");
				String errorMsg = SALESMSG + AGENTMSG + AGREEMENTMSG + SERVICECODEMSG +AGENTSALESMSG;
				return Result.error(errorMsg);
			}
		}
		//是否电子保单
		if(StrUtil.isEmpty(isEpolicy)){
			return Result.error("请选择是否电子保单");
		}
		//是否发送电子邮件
		if(StrUtil.isEmpty(EpolicyMali)){
			return Result.error("请选择是否发送电子保单");
		}
		//是否发送电子发票

		if(StrUtil.isEmpty(EpolicyInvoice)){
			return Result.error("请选择是否发送电子发票");
		}
		//发送邮件模板
		if(EpolicyMali=="1" && MailTemplate.length()==0){
			return Result.error("请输入邮件模板");
		}
		MailTemplate = URLDecoder.decode(MailTemplate, "UTF-8");
		/*//是否开通支付平台
		if(StrUtil.isEmpty(DredgePay)){
			return Result.error("请选择是否开通支付平台");
		}*/

		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				String id=jsonElement.getAsJsonObject().get("id").getAsString();
				JsonElement cardapplicant=jsonElement.getAsJsonObject().get("cardapplicant");
				if(cardapplicant==null){
					ids=ids+id+",";
				}
			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}
		}
		//是否打印单证,当“是否打印单证”的值为“是”时，单证领用人可输入( "":请选择,"Y":是，"N":否)
		if(StrUtil.isEmpty(isPrintCard)){
			return Result.error("是否打印单证不能为空");
		}else{
			if("Y".equals(isPrintCard)){
				if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
					if(StrUtil.isEmpty(cardApplicant)){
						return Result.error("单证领用人不能为空");
					}
				}
			}
		}
		//当“是否发送短信”的值为“是”时，短信模板配置
		if("Y".equals(isMessage)){
			if(StrUtil.isEmpty(messageReceiver)){
				return Result.error("请选择短信接收人");
			}
			if(StrUtil.isEmpty(messageTemplate)){
				return Result.error("短信模板配置不能为空");
			}
		}else{
			messageReceiver="";
		}
		NocarPlan ncp = new NocarPlan();

		ncp.setPlanCode(planCode);
		ncp.setProdCode(prodCode);
		ncp.setPlanName(planName);
		ncp.setPartnerCode(partnerCode);
		ncp.setChannelCode(channelCode);
		ncp.setChannelType(channelType);
		ncp.setServiceCode(serviceCode);
		ncp.setServiceName(serviceName);
		ncp.setAgentFeeConfig(agentFeeConfig);
		ncp.setAgentType(agentType);
		ncp.setCommRate(commRate);
		ncp.setIsMessage(isMessage);
		ncp.setEmpNo(empNo);
		ncp.setEmpName(empName);
		ncp.setTeamCode(teamCode);
		ncp.setTeamName(teamName);
		ncp.setBsnsType(bsnsType);
		ncp.setNewBsnsType(newBsnsType);
		ncp.setDeptCode(deptCode);
		ncp.setAgentNo(agentNo);
		ncp.setSpecialArran(specialArran);
		ncp.setStatus(status);
		ncp.setIsSeeMoney(isSeeMoney);
		ncp.setMessageReceiver(messageReceiver);
		ncp.setMessageTemplate(messageTemplate);
		ncp.setProtocolNo(protocolNo);
		ncp.setIsEpolicy(isEpolicy);
		ncp.setUpdateTime(new Date());
		ncp.setIsPrintCard(isPrintCard);
		ncp.setCardType(cardType);
		ncp.setCardApplicant(cardApplicant);
		ncp.setEpolicyInvoice(EpolicyInvoice);
		ncp.setDredgePay(DredgePay);
		ncp.setEpolicyMali(EpolicyMali);
		ncp.setMailTemplate(MailTemplate);
		ncp.setIdStr(ids);
		ncp.setDownloadWay(DownloadWay);
		ncp.setIsCancelMessage(isCancelMessage);
		ncp.setCancelReceiver(cancelReceiver);
		ncp.setCancelTemplate(cancelTemplate);
		ncp.setFileType(fileType);
		ncp.setBusinessPerformanceRate(businessPerformanceRate);
		ncp.setMarketPreserveRate(marketPreserveRate);
		ncp.setSpecialConfigType(specialConfigType);
		ncp.setInvockLink(invockLink);
		ncp.setDentification(dentification);
		ncp.setIsReceipt(isReceipt);
		ncp.setReceiptType(receiptType);
		ncp.setIsedrno(isedrno);
		ncp.setEdrnoType(edrnoType);
		ncp.setPayEinvoice(payEinvoice);
		ncp.setIsInsuranceEinvoice(isInsuranceEinvoice);
		ncp.setIsEConfirm(isEConfirm);
		ncp.setIsPushedSalesInfo(isPushedSalesInfo);
		// 如果此方案修改了产品，则同步更改方案与方案组关联，否则不做修改
		NocarPlan updateBefore = new NocarPlan();
		updateBefore.setPlanCode(planCode);
		NocarPlan oldTradInsuPlan = nocarInsureService
				.queryTradNocarPlanInfo(updateBefore);
		if (!oldTradInsuPlan.getProdCode().equals(prodCode)) {
			// 根据方案对应的产品的产品类型，查询相应方案组信息,将该方案和方案组信息维护到方案组表
			NocarProd prodTem = noCarProductService
					.queryNocarTradProdInstById(prodCode);// 得到产品类型
			// 根据产品类型得到方案组ID
			TradPlanGroup gp = new TradPlanGroup();
			gp.setProdType(prodTem.getProdType());
			TradPlanGroup pg = plangroupService.queryTradPlanGroupID(gp);
			// 维护方案与方案组关联表
			if(pg!=null){
				TradInsuPlanGroup group = new TradInsuPlanGroup();
				group.setInsuPlanNumber(planCode);
				group.setPlanGroupId(StrUtil.getVal(pg.getGroupId()));
				boolean f = insuPlanGroupService.updateTradInsuPlanGroup(group);
				if (!f) {
					return Result.error("维护方案与方案组关联出错");
				}
			}
		}

		boolean flag = nocarInsureService.updateTradNocarPlanInfo(ncp);

		if (flag) {
			logger.info("==========================修改投保方案成功=============================");

			return Result.success("修改成功");
		} else {
			logger.info("==========================修改投保方案失败=============================");
			return Result.error("修改失败");
		}
	}

	// 抽取页面的所有的字典数据控件到公共方法处理
	private List<DictDto> getPageLoadSubDropList(String codeType,String parentCode) throws Exception {
		List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType,parentCode);
		return subDataList;
	}

	// 归属渠道-渠道类型-新业务来源处理
	@RequestMapping(value = "/loadSubDropList")
	public @ResponseBody List<DictDto> getSubDropListData(String codeType, String parentCode) throws Exception {
		List<DictDto> list = new ArrayList<DictDto>();
		if (StrUtil.isNotEmpty(codeType) && StrUtil.isNotEmpty(parentCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType, parentCode);
			//复制list
			list.addAll(subDataList);
			//倒序
			Collections.reverse(list);
			DictDto dd = new DictDto();
			dd.setCode("");
			dd.setCodeName("----请选择----");
			list.add(dd);
			//倒序
			Collections.reverse(list);
			return list;
		}else{
			DictDto dd = new DictDto();
			dd.setCode("");
			if("channel_type".equals(codeType)){
				dd.setCodeName("----请选择归属渠道----");
			}else if("new_business_source".equals(codeType)){
				dd.setCodeName("----请选择渠道类型----");
			}
			list.add(dd);
		}
		return list;
	}

	//选取旧业务来源
	@RequestMapping(value = "/chooseBsnsType")
	public @ResponseBody DictDto chooseBsnsType(String parentCode,String newBsnsCode) throws Exception {
		DictDto dd = new DictDto();
		if (StrUtil.isNotEmpty(parentCode)&&StrUtil.isNotEmpty(newBsnsCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode("new_business_source", parentCode);
			for (DictDto dictDto : subDataList) {
				if(newBsnsCode.equals(dictDto.getCode())){
					return dictDto;
				}
			}
		}else{
			dd.setOtherCode("");
		}
		return dd;
	}

	@RequestMapping(value = "/loadConfProxyInfo")
	public @ResponseBody Page loadConfProxyInfo(HttpSession session, Integer size,Integer pageIndex,String channelCode,String agentType,
												String confStatus,String userName,String userCode,String insuPlanNo,
												String branch,String branchName) throws Exception{
		Page<TradAgentInfo> page=new Page<TradAgentInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		TradAgentInfo tradAgentInfo=new TradAgentInfo();
		tradAgentInfo.setAgentType(agentType);
		tradAgentInfo.setUserCode(userCode);
		page.setType(tradAgentInfo);
		//登陆用户
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("channelCode", channelCode);//机构代码
		map.put("userName", userName);//代理人名称
		map.put("confStatus", confStatus);//配置状态
		map.put("insuPlanNo", insuPlanNo);
		map.put("branch", branch);//网点
		map.put("branchName", branchName);//网点名称
		map.put("dept_code",gatewayuser.getDepartmentStr().substring(1, 3));
		/**总对总分公司权限改造*/
		map.put("dept_code4",gatewayuser.getDepartmentStr());
		Page page2=gatewayInsureService.queryPageForTradAgentInfo(page, map);
		return page2;
	}
	@RequestMapping(value = "/loadConfProxyInfoEdit")
	public @ResponseBody Page loadConfProxyInfoEdit(HttpSession session,Integer size,Integer pageIndex,String insuPlanNo,String agentType) throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		Page page=new Page();
		page.setCurrent(pageIndex);
		page.setSize(size);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("insuPlanNo", insuPlanNo);
		map.put("agentType", agentType);
		if("4".equals(agentType) || "5".equals(agentType)){
			map.put("userdeptstr", gatewayuser.getDepartmentStr());
		}
		Page page2=gatewayInsureService.queryPageForTradAgentInfoEdit(page, map);
		return page2;
	}
	@RequestMapping(value = "/loadCoinFeeList")
	public @ResponseBody Page loadCoinFeeList(Integer size,Integer pageIndex,String insuPlanNo,String agentType) throws Exception{
		Page page=new Page();
		page.setCurrent(pageIndex);
		page.setSize(size);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("insuPlanNo", insuPlanNo);
		map.put("agentType", agentType);
		Page page2=gatewayInsureService.queryPageForTradAgentInfoEdit(page, map);
		return page2;
	}
	/**
	 * 添加/修改代理信息
	 * @param session
	 * @param insuPlanNo
	 * @param agentTypeList
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateProxyInfo")
	public @ResponseBody Result updateProxyInfo(HttpSession session,String insuPlanNo,String isPrintCard,String agentTypeList) throws Exception{
		if(StrUtil.isEmpty(insuPlanNo)){
			return Result.error("方案号不能为空");
		}
		if(StrUtil.isEmpty(agentTypeList)){
			return Result.error("代理信息不能为空");
		}
		if("Y".equals(isPrintCard)){//( "":请选择,"Y":是，"N":否)
			//创建一个JsonParser
			JsonParser parser = new JsonParser();
			//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
			JsonElement el = parser.parse(agentTypeList);
			//把JsonElement对象转换成JsonArray
			JsonArray jsonArray = null;
			if(el.isJsonArray()){
				jsonArray = el.getAsJsonArray();
			}else{
				return Result.error("无效的代理信息");
			}
			for (JsonElement jsonElement : jsonArray) {
				String id =jsonElement.getAsJsonObject().get("id").getAsString();
				String cardapplicant=jsonElement.getAsJsonObject().get("cardapplicant").getAsString();
				if(StrUtil.isEmpty(id)||StrUtil.isEmpty(cardapplicant)){
					return Result.error("您配置的代理信息中存在单证领用人为空的,单证领用人不能为空");
				}
			}
		}
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);

		boolean flag = gatewayInsureService.updateProxyInfo(insuPlanNo, gatewayuser, agentTypeList);
		if(flag){
			return Result.success("更新成功");
		}else{
			return Result.error("更新失败");
		}
	}

	@RequestMapping(value = "/copyAddTradPlan")
	public @ResponseBody Result copyAddTradPlan(HttpSession session,String planCode,
												String prodCode, String prodName, String planName,
												String partnerCode, String channelCode, String channelType,
												String serviceCode, BigDecimal commRate, String isSeeMoney,
												String empNo, String teamCode, String teamName, String bsnsType, String newBsnsType, String deptCode,
												String agentNo, String specialArran, String status,
												String isMessage,String messageReceiver,String messageTemplate,
												String prodType,String protocolNo,String isEpolicy,String isPrintCard,String cardType,
												String cardApplicant,String oldPlanNo,String oldAgentType,
												String EpolicyInvoice, String DredgePay,String EpolicyMali,String MailTemplate ,String selectAccessorylistStr,String DownloadWay,String planType,String saleArry,String isCancelMessage,String cancelReceiver,String cancelTemplate,
												String agentType,String agentFeeConfig,BigDecimal businessPerformanceRate,
												BigDecimal marketPreserveRate,String specialConfigType,Boolean isProprod,String invockLink,String dentification,String isReceipt,String receiptType,String isedrno, String edrnoType,String isInsuranceEinvoice,String payEinvoice,
												String channelFlag,String isEConfirm,String isPushedSalesInfo)
			throws Exception {
		cancelTemplate=URLDecoder.decode(cancelTemplate, "UTF-8");
		boolean isCopy = false;//是否复制代理信息 标志
		NocarPlan plan =new NocarPlan();
		plan.setPlanCode(oldPlanNo);
		NocarPlan oldPlan = this.nocarInsureService.queryTradNocarPlanInfo(plan);
		//首先进行非空、格式校验
		if(StrUtil.isEmpty(planName)){
			return Result.error("请输入投保方案名称");
		}
		if(StrUtil.isEmpty(prodCode)){
			return Result.error("请选择产品编号");
		}

		NocarProd prod2 =noCarProductService.queryNocarTradProdInstById(prodCode);

		//如果产品类型与原类型相同并且 合作伙伴代码与原合作伙伴代码相同
		if(agentType.equals(oldAgentType)&&oldPlan.getPartnerCode().equals(partnerCode)){
			isCopy = true;
		}

		if(StrUtil.isEmpty(partnerCode)){
			return Result.error("请选择合作伙伴代码");
		}
		//1、合作伙伴代理3、个人代理4、总对总代理5联合出单
		if(!"1".equals(channelFlag)){

			if(!"3".equals(agentType)&&!"4".equals(agentType)&&!"6".equals(agentType) && !"5".equals(agentType)){
				if(StrUtil.isEmpty(deptCode)){
					return Result.error("请选择出单机构");
				}
				if(StrUtil.isEmpty(channelCode)){
					return Result.error("请输入归属渠道");
				}
				if(StrUtil.isEmpty(channelType)){
					return Result.error("请输入渠道类型");
				}
				if(StrUtil.isEmpty(newBsnsType)){
					return Result.error("请输入新业务来源");
				}
				if(StrUtil.isEmpty(bsnsType)){
					return Result.error("请输入原业务来源");
				}
			}

		}
		if(!"2".equals(agentFeeConfig)){
			if(null == commRate){
				return Result.error("请输入手续费比例");
			}else{
				Pattern pattern = Pattern.compile("([1-9]\\d{0,15}|0)(\\.\\d{1,6})?");
				Matcher matcher = pattern.matcher(commRate.toString());
				if(!matcher.matches()){
					return Result.error("手续费比例为长度不超过16位数字且最多保留6位小数的有效数字");
				}
				float tem = commRate.floatValue();
				if (!(0 <= tem && tem <= 1)) {
					return Result.error("手续费比例：只能录入大于等于0且小于等于1的数字！");
				}
			}
		}
		//产品销售类型为代理类型
		if("3".equals(agentType)||("4".equals(agentType)&&!"1".equals(channelFlag))){
			if(agentType.equals(oldAgentType)&&oldPlan.getPartnerCode().equals(partnerCode)){
				if("1".equals(status)){
					if(gatewayInsureService.proxyInfoIsEmpty(oldPlanNo)){
						return Result.error("原方案未配置代理信息,该方案不能置为有效");
					}
				}
			}else{
				if("1".equals(status)){
					return Result.error("方案销售类型更改或合作伙伴更改,该方案不能置为有效");
				}
			}
		}
		if(!"1".equals(channelFlag)){

			//1、合作伙伴代理3、个人代理4、总对总代理
			if(!"3".equals(agentType)&&!"4".equals(agentType)&&!"6".equals(agentType) && !"5".equals(agentType)){
				if(StrUtil.isEmpty(serviceCode)){
					return Result.error("请输入服务代码");
				}
				if(StrUtil.isEmpty(empNo)){
					return Result.error("请输入业务员代码");
				}
				//原业务来源为19002-代理或19003-经纪，则代理人代码和代理协议号必填，其他非必填
				if("19002".equals(bsnsType)||"19003".equals(bsnsType)){
					if(StrUtil.isEmpty(agentNo)){
						return Result.error("请输入代理人代码");
					}
					if(StrUtil.isEmpty(protocolNo)){
						return Result.error("请输入代理协议号");
					}
				}
			}

		}
		//是否发送电子邮件
		if(StrUtil.isEmpty(EpolicyMali)){
			return Result.error("请选择是否发送电子保单");
		}
		//是否发送电子发票

		if(StrUtil.isEmpty(EpolicyInvoice)){
			return Result.error("请选择是否发送电子发票");
		}
		//发送邮件模板
		if(EpolicyMali=="1" && MailTemplate.length()==0){
			return Result.error("请输入邮件模板");
		}
		MailTemplate = URLDecoder.decode(MailTemplate, "UTF-8");
		/*//是否开通支付平台
		if(StrUtil.isEmpty(DredgePay)){
			return Result.error("请选择是否开通支付平台");
		}*/

		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				String id=jsonElement.getAsJsonObject().get("id").getAsString();
				JsonElement cardapplicant=jsonElement.getAsJsonObject().get("cardapplicant");
				if(cardapplicant==null){
					ids=ids+id+",";
				}
			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}
		}
		//是否打印单证,当“是否打印单证”的值为“是”时，单证领用人可输入( "":请选择,"Y":是，"N":否)
		if(StrUtil.isEmpty(isPrintCard)){
			return Result.error("是否打印单证不能为空");
		}else{
			if("Y".equals(isPrintCard)){
				if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
					if(StrUtil.isEmpty(cardApplicant)){
						return Result.error("单证领用人不能为空");
					}
				}
			}
		}
		//当“是否发送短信”的值为“是”时，短信模板配置
		if("Y".equals(isMessage)){
			if(StrUtil.isEmpty(messageReceiver)){
				return Result.error("请选择短信接收人");
			}
			if(StrUtil.isEmpty(messageTemplate)){
				return Result.error("短信模板配置不能为空");
			}
		}else{
			messageReceiver="";
		}
//		NocarPlan tem  = new NocarPlan();
		NocarPlan ncp  = new NocarPlan();

		String planflag="NOCAR";
		String isFlag="-";
		if (isProprod) {
			planflag="CIC"+prod2.getProdType();
			isFlag="";
		}
		NocarPlan tem = nocarInsureService.getMaxPlanCodeFromDB(planflag+"%");
		if (null == tem||StrUtil.isEmpty(tem.getPlanCode())) {
			ncp.setPlanCode(planflag+isFlag+"00001");
		} else {
			String maxNo = tem.getPlanCode().substring(tem.getPlanCode().length()-5);
			logger.info("----------------------------------"+ maxNo);
			int nextNoVal = Integer.parseInt(maxNo);
			nextNoVal = nextNoVal + 1;
			logger.info("-------------------------------------"+ nextNoVal);
			// 不足5位，补0
			String nextInsuPlanNo = (planflag+isFlag).concat(String.format("%05d",nextNoVal));
			ncp.setPlanCode(nextInsuPlanNo);
		}
		ncp.setProdCode(prodCode);
		ncp.setPlanName(planName);
		ncp.setPartnerCode(partnerCode);
		ncp.setChannelCode(channelCode);
		ncp.setChannelType(channelType);
		ncp.setServiceCode(serviceCode);
		ncp.setCommRate(commRate);
		ncp.setIsMessage(isMessage);
		ncp.setEmpNo(empNo);
		ncp.setTeamCode(teamCode);
		ncp.setTeamName(teamName);
		ncp.setBsnsType(bsnsType);
		ncp.setNewBsnsType(newBsnsType);
		ncp.setDeptCode(deptCode);
		ncp.setAgentNo(agentNo);
		ncp.setSpecialArran(specialArran);
		ncp.setStatus(status);
		ncp.setIsSeeMoney(isSeeMoney);
		ncp.setProtocolNo(protocolNo);
		ncp.setMessageReceiver(messageReceiver);
		ncp.setMessageTemplate(messageTemplate);
		ncp.setIsEpolicy(isEpolicy);
		ncp.setInsertTime(new Date());
		ncp.setIsPrintCard(isPrintCard);
		ncp.setCardType(cardType);
		ncp.setCardApplicant(cardApplicant);
		ncp.setEpolicyInvoice(EpolicyInvoice);
		ncp.setDredgePay(DredgePay);
		ncp.setEpolicyMali(EpolicyMali);
		ncp.setMailTemplate(MailTemplate);
		ncp.setIdStr(ids);
		ncp.setAgentType(agentType);
		ncp.setAgentFeeConfig(agentFeeConfig);
		ncp.setDownloadWay(DownloadWay);
		ncp.setIsCancelMessage(isCancelMessage);
		ncp.setCancelReceiver(cancelReceiver);
		ncp.setCancelTemplate(cancelTemplate);
		ncp.setMarketPreserveRate(marketPreserveRate);
		ncp.setBusinessPerformanceRate(businessPerformanceRate);
		ncp.setSpecialConfigType(specialConfigType);
		ncp.setInvockLink(invockLink);
		ncp.setDentification(dentification);
		ncp.setIsReceipt(isReceipt);
		ncp.setReceiptType(receiptType);
		ncp.setIsedrno(isedrno);
		ncp.setEdrnoType(edrnoType);
		ncp.setPayEinvoice(payEinvoice);
		ncp.setIsInsuranceEinvoice(isInsuranceEinvoice);
		ncp.setIsEConfirm(isEConfirm);
		ncp.setIsPushedSalesInfo(isPushedSalesInfo);
		boolean flag = nocarInsureService.copyAddTradNocarPlan(ncp, oldPlanNo, isCopy);
		if (flag) {
			logger.info("==========================添加投保方案成功=============================");
			// 根据方案对应的产品的产品类型，查询相应方案组信息,将该方案和方案组信息维护到方案与方案组关联表
			// 根据产品类型得到方案组ID
			TradPlanGroup gp = new TradPlanGroup();
			gp.setProdType(prodType);
			TradPlanGroup pg = plangroupService.queryTradPlanGroupID(gp);
			// 维护方案与方案组关联表
			if(pg!=null){
				TradInsuPlanGroup group = new TradInsuPlanGroup();
				group.setInsuPlanNumber(ncp.getPlanCode());// insuPlanNo; //产品类型代码
				group.setPlanGroupId(StrUtil.getVal(pg.getGroupId()));
				group.setRequired("0");
				boolean f = insuPlanGroupService.addTradInsuPlanGroup(group);
				if (!f) {
					return Result.error("维护方案与方案组关联出错");
				}
			}
			//销售人员信息
			if(StrUtil.isNotEmpty(deptCode)){
				if(deptCode.startsWith("44")){
					addTradSale(ncp.getPlanCode(), planType, saleArry);
				}
			}
			Map<String,String>  resultMap =new  HashMap<String,String>();
			resultMap.put("InsuPlanNo", ncp.getPlanCode());
			resultMap.put("AgentType", agentType);
			resultMap.put("agentFeeConfig", agentFeeConfig);
			return Result.successAndData("添加成功",resultMap);
		} else {
			logger.info("==========================添加投保方案失败=============================");
			return Result.error("添加失败");
		}
	}

	/**
	 * 查询业务员-团队信息(从销管获取)
	 * @param COMCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querySauserAndTeamInfo")
	@ResponseBody
	public Result querySauserAndTeamInfo(String COMCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)){
			return Result.error("出单机构不能为空");
		}

		Result result = null;
		try{
			result = nlifePlanConfigService.querySauserAndTeamInfo(COMCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询中介-协议信息(从销管获取)
	 * @param COMCODE
	 * @param TEAMCODE
	 * @param BUSINESSSOURCE
	 * @param CHANNELNAME
	 * @param PRODCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryAgentAndAgreeInfo")
	@ResponseBody
	public Result queryAgentAndAgreeInfo(String COMCODE,String TEAMCODE,
										 String BUSINESSSOURCE,String CHANNELNAME,String PRODCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)) return Result.error("出单机构不能为空");
		if(StrUtil.isEmpty(TEAMCODE)) return Result.error("团队代码不能为空");
		if(StrUtil.isEmpty(BUSINESSSOURCE)) return Result.error("业务来源不能为空");
		if(StrUtil.isEmpty(CHANNELNAME)) return Result.error("渠道名称不能为空");
		if(StrUtil.isEmpty(PRODCODE)) return Result.error("产品代码不能为空");
		PRODCODE = PRODCODE.substring(0, 4);
		Result result = null;
		try{
			result = nlifePlanConfigService.queryAgentAndAgreeInfo(COMCODE, TEAMCODE, BUSINESSSOURCE, CHANNELNAME, PRODCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}

	/**
	 * 查询服务代码信息(从销管获取)
	 * @param COMCODE
	 * @param BUSINESSSOURCE
	 * @param CHANNELNAME
	 * @param USERCODE
	 * @param AGENTCODE
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryServiceNo")
	@ResponseBody
	public Result queryServiceNo(String COMCODE,String BUSINESSSOURCE,
								 String CHANNELNAME,String USERCODE,String AGENTCODE) throws Exception {
		if(StrUtil.isEmpty(COMCODE)) return Result.error("出单机构不能为空");
		if(StrUtil.isEmpty(BUSINESSSOURCE)) return Result.error("业务来源不能为空");
		if(StrUtil.isEmpty(CHANNELNAME)) return Result.error("渠道名称不能为空");
		if(StrUtil.isEmpty(USERCODE)) return Result.error("业务员代码不能为空");

		Result result = null;
		try{
			result = nlifePlanConfigService.queryServiceNo(COMCODE, BUSINESSSOURCE, CHANNELNAME, USERCODE, AGENTCODE);
		}catch(Exception e){
			logger.info(e);
			return Result.error(e.getMessage());
		}
		return result;
	}
	/***
	 * 销售信息保存
	 */
	@RequestMapping(value = "/addTradPlanSale")
	@ResponseBody
	public Result addTradPlanSale(String planCode,String planType,String saleArry) throws Exception {
		return addTradSale(planCode, planType, saleArry);
	}
	private Result addTradSale(String planCode,String planType,String saleArry) throws Exception{
		Result result = null;
		if(planCode!=null&&!"".equals(planCode)){
			Map<String, String> map=new HashMap<String, String>();
			map.put("planCode", planCode);
			tradPlanSaleService.deleteTrade(map);
			List<Map<String,String>> list = JsonUtils.parseJson(saleArry, ArrayList.class);
			List<TradPlanSale> planSales=new ArrayList<TradPlanSale>();
			for (Map<String, String> map2 : list) {
				TradPlanSale planSale=new TradPlanSale();
				planSale.setAgentFee((Double.parseDouble(map2.get("agentFee"))));
				planSale.setAgentNo(map2.get("agentNo"));
				planSale.setEmpNo(map2.get("empNo"));
				planSale.setPersonType(map2.get("personType"));
				planSale.setPracticeNo(map2.get("practiceNo"));
				planSale.setSalePerson(map2.get("salePerson"));
				planSale.setSaleType(map2.get("saleType"));
				planSale.setSeqNo(map2.get("seqNo"));
				planSale.setPlanNo(planCode);
				planSale.setInsertDate(new Date());
				planSale.setPlanType(planType);
				planSales.add(planSale);
			}
			Boolean flag=tradPlanSaleService.addTrade(planSales);
			if(flag){
				result=Result.success("添加成功");
			}else{
				result=Result.error("添加失败");
			}
		}else{
			result=Result.error("方案号为空");
		}
		return result;

	}
	/**
	 * 加载数据字典
	 * @param planNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadDic")
	@ResponseBody
	public Map<String,Object> loadDic() throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		/**人员类别字典*/
		List<DictDto> saleMenTypes=DictCache.getDict(Constants.DICT_SALE_MEN_TYPE);
		/**销售员类型**/
		List<DictDto> saleTypes=DictCache.getDict(Constants.DICT_SALES_TYPE);
		map.put("saleMenTypes", saleMenTypes);
		map.put("saleTypes", saleTypes);
		return map;
	}
	/**
	 * 跟单配置信息，与方案关联保存
	 * @param page
	 * @param planNo
	 * @param agentType
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveCoinPlan")
	@ResponseBody
	public Map<String,Object> saveCoinPlan(CoinPlanConfig coin) throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			if(coinPlanConfigService.saveCoinPlan(coin)){
				map.put("success", true);
			}else{
				map.put("success", false);
			}
		} catch (Exception e) {
			map.put("success", false);
			logger.info("数据库操作错误",e);
		}
		return map;
	}

	/**
	 * 查询电子邮件模板列表
	 */
	@RequestMapping(value = "/queryEmailTempList")
	@ResponseBody
	public Map<String,Object> queryEmailTempList() throws Exception{
		Map<String, Object> map=new HashMap<String, Object>();
		List<TradEmailTemplate> emailTemplates=tradEmailTemplateService.queryList();
		map.put("templates", emailTemplates);

		return map;
	}

	public String selectSingleNodeByRoot(Element root,String path){
		Node node = root.selectSingleNode(path);
		if(node==null){
			return "";
		}else{
			return node.getText();
		}
	}

	private String getAgentTypeByNewBsnsType(String newBsnsType,List<DictDto> newBusinessSource) {
		String agentType = "";
		for (DictDto dictDto : newBusinessSource) {
			if (newBsnsType.equals(dictDto.getCode())){
				if ("1900101".equals(dictDto.getOtherCode2())){
					agentType = "0";
					break;
				}else if ("1900203".equals(dictDto.getOtherCode2())) {
					agentType = "1";
					break;
				}else if ("1900201".equals(dictDto.getOtherCode2())) {
					agentType = "2";
					break;
				}else if ("1900202".equals(dictDto.getOtherCode2())) {
					agentType = "3";
					break;
				}else if ("1900301".equals(dictDto.getOtherCode2())) {
					agentType = "4";
					break;
				}
			}
		}
		return agentType;
	}
}
